package org.kl.bf.service.basic;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.Role;
import org.kl.bf.repository.basic.RoleDao;
import org.kl.bf.repository.basic.RoleUserDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Qken
 * @date 2014-3-24
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class RoleService {

	private RoleDao roleDao;
	private JdbcTemplate jdbcTemp;
	private RoleUserDao roleUserDao;

	@Resource
	public void setDataSource(DataSource dataSource) {
		jdbcTemp = new JdbcTemplate(dataSource);
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public Role getRoleByRoleNo(String roleNo) {
		return roleDao.getRoleByRoleNo(roleNo);
	}
	
	public Role findByRoleNo(String roleNo){
		return roleDao.findByRoleNo(roleNo);
	}

	public Role getRole(String guid) {
		// return roleDao.find(Role.class,guid);
		return roleDao.findOne(guid);
	}

	public void saveRole(Role entity) {
		roleDao.save(entity);
	}

	public void deleteRole(String guid) {
		roleDao.delete(guid);
	}
	
	/**
	 * 获取某个角色的所有用户Id
	 */
	public List<String> getUsersIdByRoleNo(String roleNo) {
		Role role = roleDao.findByRoleNo(roleNo);
		return roleUserDao.getUserIds(role.getId());
	}


	public List<Role> getAllRole(Map<String, Object> searchParams, String sortType, String orderType) {
		Sort sort = CRUDUtils.buildSort(sortType, orderType);
		Specification<Role> spec = buildSpecification(searchParams);
		return (List<Role>) roleDao.findAll(spec, sort);
	}

	public Page<Role> getRole(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<Role> spec = buildSpecification(searchParams);
		return roleDao.findAll(spec, pageRequest);
	}

	/**
	 * 删除多条记录
	 * 
	 * @param ids
	 */
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				roleDao.delete(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Role> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<Role> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), Role.class);
		return spec;
	}

	/**
	 * 增加用户角色
	 * 
	 * @param roleId
	 * @param menuIds
	 *            menuId集合，用逗号分割
	 */
	public void addRoleRights(String roleId, String menuIds, String functionIds) {
		Role role = roleDao.findOne(roleId);
		if (role != null) {
			// role.setRoleMenus(new HashSet<Menu>());
			StringBuilder sql = new StringBuilder("delete from basic_role_menu where role_id ='");
			sql.append(role.getId() + "'");
			jdbcTemp.execute(sql.toString());
			for (String menuId : menuIds.split(",")) {
				if (StringUtils.isNotBlank(menuId)) {
					// Menu menu = new Menu();
					// menu.setId(menuId);
					// role.getRoleMenus().add(menu);
					sql = new StringBuilder("insert into basic_role_menu  values(");
					sql.append("'" + menuId + "','" + roleId + "')");
					jdbcTemp.update(sql.toString());
				}
			}
			// role.setRoleFunctions(new HashSet<Function>());
			sql = null;
			sql = new StringBuilder("delete from basic_role_function where role_id ='");
			sql.append(role.getId() + "'");
			jdbcTemp.execute(sql.toString());
			for (String functionId : functionIds.split(",")) {
				if (StringUtils.isNotBlank(functionId)) {
					// Function function = new Function();
					// function.setId(functionId);
					// role.getRoleFunctions().add(function);
					sql = new StringBuilder("insert into basic_role_function  values(");
					sql.append("'" + functionId + "','" + roleId + "')");
					jdbcTemp.update(sql.toString());
				}
			}
		}
		roleDao.save(role);
	}

	/**
	 * 通过roleId获取menuId List，然后循环获取对应的List<Menu>
	 * 
	 * @param roleId
	 * @return
	 */
	public List<String> getMenuList(String roleId) {
		final List<String> result = new ArrayList<String>();
		StringBuilder sql = new StringBuilder("select t.menu_id from basic_role_menu  t where t.role_id ='");
		sql.append(roleId + "'");
		jdbcTemp.query(sql.toString(), new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				result.add(rs.getString("menu_id"));
			}
		});
		return result;
	}

	public List<String> getFunctionList(String roleId) {
		final List<String> result = new ArrayList<String>();
		StringBuilder sql = new StringBuilder("select t.function_id from basic_role_function  t where t.role_id ='");
		sql.append(roleId + "'");
		jdbcTemp.query(sql.toString(), new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				result.add(rs.getString("function_id"));
			}
		});
		return result;
	}

	public List<Role> getAll(Map<String, Object> searchParams, String sortType,String orderType) {
		Specification<Role> spec = KLDynamicSpecifications.buildSpecification(searchParams, Role.class);
		return roleDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

}
